package org.mainlove.project.web.framework.util;

import java.io.File;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.Map;

import freemarker.template.Configuration;
import freemarker.template.DefaultObjectWrapper;
import freemarker.template.Template;

@SuppressWarnings("rawtypes")
public class TemplateConfiguration {

	private static Configuration configuration;

	private static String templateRoot;

	public static void setTemplateRoot(String templateRoot) {
		TemplateConfiguration.templateRoot = templateRoot;
	}

	private TemplateConfiguration() {

	};

	public static Configuration getConfiguration() throws Exception {

		if (configuration == null) {

			configuration = new Configuration();

			configuration.setDirectoryForTemplateLoading(new File(templateRoot));

			configuration.setObjectWrapper(new DefaultObjectWrapper());

		}
		return configuration;

	}

	public static Template getTemplate(String tempalteName) throws Exception {
		return getConfiguration().getTemplate(tempalteName);
	}

	public static void writeToOut(Template template, Map root) throws Exception {
		Writer out = new OutputStreamWriter(System.out);
		template.process(root, out);
		out.flush();
	}

}
